const { Op } = require('sequelize')
const Cart = require('../model/carts.model')
const Goods = require('../model/good.model')
class CartsService {
    async createOrUpdate(user_id, goods_id) {
        let res = await Cart.findOne({
            where: {
                [Op.and]: {
                    user_id,
                    goods_id
                }
            }
        })
        if (res) {
            // 已经有一条记录，增加数量
            await res.increment('number')
            return await res.reload()
        } else {
            return await Cart.create({
                user_id,
                goods_id,
            })
        }

    }
    async findCarts(pageSize, pageNum) {
        const offset = (pageNum - 1) * pageSize
        const { count, rows } = await Cart.findAndCountAll({
            attributes: ['id', 'number', 'selected'],
            offset: offset,
            limit: pageSize * 1,
            include: {
                model: Goods,
                as: 'goods_info',
                attributes: ['id', 'goods_name', 'goods_price', 'goods_img']
            },
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }

    }
}
module.exports = new CartsService()